﻿/**
* Node 移动器。
*/
Ext.define('Happy.designer.NodeDrager', {

    constructor: function (designer) {
        var me = this;

        me.designer = designer;
        me.drawer = designer.drawer;

        me.designer.mon(me.designer.getEl(), 'mousemove', me.onDesignerMouseMoveHandler, me);
        me.designer.mon(me.designer.getEl(), 'mouseup', me.onDesignerMouseUpHandler, me);
    },

    /**
     * 允许节点被移动。
     * 
     * @public
     * @param {Happy.designer.Node} node 节点实例
     */
    allowDrag: function (node) {
        var me = this;

        node.shape.mon(node.shape, 'mousedown', Ext.Function.bind(me.onShapeMouseDownHandler, me, [node], true));
        setTimeout(function () {
            node.shape.setStyle({ 'cursor': 'move' });
        }, 0);
    },

    /**
     * @private
     */
    onShapeMouseDownHandler: function (shape, e, option, node) {
        var me = this;

        me.startDrag(node, e.getX(), e.getY());

        e.stopEvent();
    },

    /**
     * @private
     */
    onDesignerMouseMoveHandler: function (e) {
        var me = this;

        me.onDrag(e);
    },

    /**
     * @private
     */
    onDesignerMouseUpHandler: function () {
        var me = this;

        me.stopDrag();
    },

    /**
     * 开始移动节点。
     * 
     * @private
     * @param {Happy.designer.Node} node 节点实例
     * @param {Number} x 开始移动的 x 坐标（相对于 Page）
     * @param {Number} y 开始移动的 y 坐标（相对于 Page）
     */
    startDrag: function (node, x, y) {
        var me = this;

        me.currentDragNode = node;
        me.prevXY = [x, y];
    },

    /**
     * 移动节点。
     * 
     * @private
     * @param {Ext.EventObject} e 事件对象
     */
    onDrag: function (e) {
        var me = this;

        if (!me.currentDragNode) {
            return;
        }

        var currentXY = [e.getX(), e.getY()];

        var dx = currentXY[0] - me.prevXY[0];
        var dy = currentXY[1] - me.prevXY[1];

        me.currentDragNode.move(dx, dy);

        me.prevXY = currentXY;
    },

    /**
     * 停止移动。
     * 
     * @private
     */
    stopDrag: function () {
        var me = this;

        if (!me.currentDragNode) {
            return;
        }

        me.currentDragNode = null;
        me.prevXY = null;
    }
});
